package com.yuzhi.master.drainSms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yuzhi.common.core.page.PageDataInfo;
import com.yuzhi.common.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.dromara.sms4j.provider.enumerate.SupplierType;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.yuzhi.master.drainSms.domain.bo.DrainSmsInfoBo;
import com.yuzhi.master.drainSms.domain.vo.DrainSmsInfoVo;
import com.yuzhi.master.drainSms.domain.request.DrainSmsInfoReq;
import com.yuzhi.master.drainSms.domain.DrainSmsInfo;
import com.yuzhi.master.drainSms.mapper.DrainSmsInfoMapper;
import com.yuzhi.master.drainSms.service.IDrainSmsInfoService;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 短信消息明细Service业务层处理
 *
 * @author coding123
 * @date 2025-08-29
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class DrainSmsInfoServiceImpl implements IDrainSmsInfoService {

    private final DrainSmsInfoMapper baseMapper;

    /**
     * 查询短信消息明细
     */
    @Override
    public DrainSmsInfoVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询短信消息明细列表
     */
    @Override
    public PageDataInfo<DrainSmsInfoVo> queryPageList(DrainSmsInfoReq request) {
        LambdaQueryWrapper<DrainSmsInfo> lqw = buildQueryWrapper(request);
        Page<DrainSmsInfoVo> result = baseMapper.selectVoPage(request.getPageQuery().build(), lqw);
        return PageDataInfo.build(result);
    }

    /**
     * 查询短信消息明细列表
     */
    @Override
    public List<DrainSmsInfoVo> queryList(DrainSmsInfoReq request) {
        LambdaQueryWrapper<DrainSmsInfo> lqw = buildQueryWrapper(request);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DrainSmsInfo> buildQueryWrapper(DrainSmsInfoReq request) {
        Map<String, Object> params = request.getParams();
        LambdaQueryWrapper<DrainSmsInfo> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(request.getSendPhonenumber()), DrainSmsInfo::getSendPhonenumber, request.getSendPhonenumber());
        if(request.getQueryStartTime()!=null && request.getQueryEndTime()!=null)
        {
            LocalDateTime startTime = request.getQueryStartTime().toLocalDate().atStartOfDay();
            LocalDateTime  endTime = request.getQueryEndTime().toLocalDate().atTime(LocalTime.MAX);
            lqw.between(DrainSmsInfo::getSendTime,startTime,endTime);
        }
        lqw.orderByDesc(DrainSmsInfo::getSendTime);
        return lqw;
    }

    /**
     * 新增短信消息明细
     */
    @Override
    public Boolean insertByBo(DrainSmsInfoBo bo) {
        DrainSmsInfo add = BeanUtil.toBean(bo, DrainSmsInfo.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setSendPhonenumber(add.getSendPhonenumber());
        }
        return flag;
    }

    /**
     * 修改短信消息明细
     */
    @Override
    public Boolean updateByBo(DrainSmsInfoBo bo) {
        DrainSmsInfo update = BeanUtil.toBean(bo, DrainSmsInfo.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(DrainSmsInfo entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除短信消息明细
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 根据id删除短信消息明细信息
     */
    @Override
    public Boolean deleteById(String id, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteById(id) > 0;
    }


    /**
     * 调用短信服务发送短信并记录日志
     * @param phonenumber  手机号码
     * @param msg  短信内容
     * @param templateId 短信模板
     * @param map 短信模板内容参数
     * @return
     */
    @Override
    public SmsResponse  sendSmsInfo(String phonenumber,String smsType, String msg, String templateId, LinkedHashMap<String, String> map )
    {
        //短信发送结果(0:失败  1:成功)
        String smsResult = "0";
        //发送 腾讯云短信
        SmsBlend smsBlend = SmsFactory.createSmsBlend(SupplierType.TENCENT);
        SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, templateId, map);
        if ("OK".equalsIgnoreCase(smsResponse.getCode())) {
            smsResult = "1";
        }

        DrainSmsInfoBo  smsInfoBo  = new DrainSmsInfoBo();
        smsInfoBo.setSendPhonenumber(phonenumber); //手机号码
        smsInfoBo.setSmsMsg(msg);  //消息内容
        smsInfoBo.setSendTime(LocalDateTime.now());  //发送时间
        smsInfoBo.setSmsResult(smsResult);  //发送结果
        smsInfoBo.setSmsType(smsType);  //短信消息类型(1:验证码 2:待办通知)
        smsInfoBo.setSmsCode(smsResponse.getMessage());

        this.insertByBo(smsInfoBo);

        return smsResponse;
    }


}
